using System.Windows.Controls;
using System.Windows.Input;

namespace jSLCore.Client.Presentation.Controls
{
    public class jPasswordBox : TextBox
    {
        private string password = string.Empty;
        public string Password { get { return password; } }

        public jPasswordBox()
        {
            TextChanged += PasswordBox_TextChanged;
        }

        private bool isSettingText = false;

        void PasswordBox_TextChanged(object sender, TextChangedEventArgs e)
        {

            if (!isSettingText)
            {
                int pPos = 0;
                for (int i = 0; i < Text.Length; i++)
                {
                    var ch = Text[i];

                    if (ch == '*')
                    {
                        pPos++;
                        continue;
                    }
                    else
                    {
                        password = password.Insert(pPos, ch.ToString());
                    }
                    pPos++;
                }
                isSettingText = true;
                Text = string.Empty.PadLeft(Text.Length, '*');
                Select(Text.Length, 0);
                isSettingText = false;
            }
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            if (e.Key == Key.Ctrl
                ||
                e.Key == Key.Back
                || e.Key == Key.Delete)
            {
                password = Text = string.Empty;
                
                e.Handled = true;
            }
        }

        
    }
}